/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cz.muni.fi.pa165.springapplication.dao.impl;


import cz.muni.fi.pa165.springapplication.dao.impl.CustomerManagerImpl;
import cz.muni.fi.pa165.springapplication.dao.CustomerManager;
import cz.muni.fi.pa165.springapplication.entities.Customer;
import cz.muni.fi.pa165.springapplication.exceptions.NonexistentEntityException;
import cz.muni.fi.pa165.springapplication.exceptions.IllegalOrphanException;
import cz.muni.fi.pa165.springapplication.exceptions.PreexistingEntityException;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Daniel Sák, 374560
 */
@Repository
public class CustomerManagerImpl implements Serializable, CustomerManager {

    @PersistenceContext(type=PersistenceContextType.EXTENDED)
    private EntityManager em;
    
    private CustomerManager custMngr;
    
    public void setEntityManager(EntityManager em){
        this.em = em;
    }
    
    @Override
    public void createCustomer(Customer customer) throws IllegalOrphanException, PreexistingEntityException {
        if(customer==null){
            throw new IllegalArgumentException();
        }
        if(customer.getId()!=null){
            throw new IllegalArgumentException("id is null");
        }
       
       
        em.persist(customer);
    }
    
    @Override
    public void updateCustomer(Customer customer) throws IllegalOrphanException, PreexistingEntityException, NonexistentEntityException, Exception{
        if(customer==null)
        {
            throw new IllegalArgumentException();
        }
        if(customer.getId()==null){
            throw new IllegalArgumentException("id is null");
        }
        
            em.merge(customer);
    }
    
    @Override
    public void deleteCustomer(Customer customer) throws NonexistentEntityException, IllegalOrphanException {
        if(customer == null){
            throw new IllegalArgumentException("Customer is null");
        }
        if(customer.getId()==null){
            throw new IllegalArgumentException("id is null");
        }
       
                em.remove(em.merge(customer));
                customer.setId(null);
            
    }
    @Override
    public Customer getCustomerById(Long id){
        Customer customer = em.find(Customer.class, id);
        return customer;
    }
    
   
    
}